<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\RewardLogsRequest;
use App\Http\Requests\UsersActiveAssociationRequest;
use App\Models\Admin\RewardLogs;
use App\Models\Admin\UsersActiveAssociation;
use App\Http\Requests\UsersActiveRequest;
use App\Models\Admin\UsersActive;
use App\Service\CacheService;
use App\Service\HttpService;
use App\Service\MiniProgramService;
use App\Service\RewardLogsService;
use App\Service\UploadsService;
use App\Service\UsersActiveAssociationService;
use App\Service\UsersService;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
use App\Service\UsersActiveService;

class UsersActiveController extends BaseController
{
    const FIRST_PRIZE_COUNT = 10;
    const SECOND_PRIZE_COUNT = 15;
    const THIRD_PRIZE_COUNT = 20;
    /**
     * 管理员列表
     * @param Request $request
     * @param UsersActive $users
     * @return Factory|View
     * @author:
     * @date: 2019/5/17 15:22
     */
    public function index(Request $request, UsersActive $users)
    {
        $params = $request->except('_token');
        $where = [];
        if (isset($params['keywords'])) {
            $where = [
                ['active_name', 'like', '%' . $params['keywords'] . '%', 'or'],
                //['mobile', 'like', '%' . $params['keywords'] . '%', 'or'],
                //['email', 'like', '%' . $params['keywords'] . '%', 'or']
            ];
        }
        $usersList = $users->getUsers($where);
        return view('admin.active.index', [
            'request' => $request,
            'search' => $params,
            'usersList' => $usersList
        ]);
    }

    /**
     *  添加活动模板
     * @return Factory|View
     * @author:
     * @date: 2019/5/20 19:14
     */
    public function add()
    {
        return view('admin.active.add');
    }

    /**
     * 添加用户操作
     * @param UsersActiveRequest $request
     * @param UsersActiveService $usersService
     * @return false|string
     * @throws \Exception
     * @author:
     * @date: 2019/5/24 18:00
     */
    public function add_active(UsersActiveRequest $request, UsersActiveService $usersService)
    {
        $params = $request->except(['_token']);

        $params['reward_level'] = \GuzzleHttp\json_encode(
            [
                ['level' => 0, 'key' => '一等奖', 'content' => $params['level_reward1']],
                ['level' => 1, 'key' => '二等奖', 'content' => $params['level_reward2']],
                ['level' => 2, 'key' => '三等奖', 'content' => $params['level_reward2']],
            ],
        );
        DB::beginTransaction();
        try {
            unset($params['level_reward1']);
            unset($params['level_reward2']);
            unset($params['level_reward3']);
            $addUsers = $usersService->store($params);
            if (!$addUsers) {
                throw new \Exception('数据库操作异常');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorReturn(10001, $e->getMessage());
        }
        DB::commit();
        return $this->successReturn();
    }

    /**
     * 用户详情
     * @param $id
     * @param UsersActiveService $usersService
     * @return Factory|View
     * @author:
     * @date: 2019/5/20 19:15
     */
    public function edit($id, UsersActiveService $usersService)
    {
        $active = $usersService->get($id);
        $reward = \GuzzleHttp\json_decode($active->reward_level);
        $active->level_reward1 = $reward[0]->content;
        $active->level_reward2 = $reward[1]->content;
        $active->level_reward3 = $reward[2]->content;
        return view('admin.active.edit', [
            'active' => $active
        ]);
    }

    /**
     * 更新用户信息
     * @param UsersActiveRequest $request
     * @param UsersActiveService $activeService
     * @return false|string
     * @author:
     * @date: 2019/5/20 19:50
     */
    public function update(UsersActiveRequest $request, UsersActiveService $activeService)
    {
        $params = $request->except(['_token']);

        $params['reward_level'] = \GuzzleHttp\json_encode(
            [
                ['level' => 0, 'key' => '一等奖', 'content' => $params['level_reward1']],
                ['level' => 1, 'key' => '二等奖', 'content' => $params['level_reward2']],
                ['level' => 2, 'key' => '三等奖', 'content' => $params['level_reward3']],
            ],
        );
        if ($params['id']) {
            DB::beginTransaction();
            try {
                unset($params['level_reward1']);
                unset($params['level_reward2']);
                unset($params['level_reward3']);
                $updateUsers = $activeService->update($params);
                if (!$updateUsers) {
                    throw new \Exception('用户信息编辑出错');
                }
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->errorReturn(10001, $e->getMessage());
            }
            DB::commit();
            return $this->successReturn();
        }

        return $activeService->update($params) ? $this->successReturn() : $this->errorReturn(10001, '用户信息编辑出错');

    }

    /**
     * 删除用户信息
     * @param Request $request
     * @param UsersActiveService $activeService
     * @return false|string
     * @author:
     * @date: 2019/5/20 20:27
     */
    public function delete(Request $request, UsersActiveService $activeService)
    {
        return $activeService->delete($request->id) ? $this->successReturn() : $this->errorReturn();
    }

    /**
     * 参与活动列表
     * @param Request $request
     * @param UsersActiveAssociation $users
     * @return Factory|View
     * @author:
     * @date: 2019/5/17 15:22
     */
    public function users_lists(Request $request, UsersActiveAssociation $users)
    {
        $params = $request->except('_token');
        $where = ['active_id' => $request->id];
        if (isset($params['keywords'])) {
            $where = [
                ['name', 'like', '%' . $params['keywords'] . '%', 'or'],
                ['active_name', 'like', '%' . $params['keywords'] . '%', 'or'],
                ['mobile', 'like', '%' . $params['keywords'] . '%', 'or']
            ];
        }
        $usersList = $users->getUsers($where);
        return view('admin.active.users_lists', [
            'request' => $request,
            'search' => $params,
            'usersList' => $usersList
        ]);
    }

    /**
     * 删除用户信息
     * @param Request $request
     * @param UsersActiveAssociationService $activeService
     * @param UsersActiveAssociationService $activeAssociationService
     * @return false|string
     * @author:
     * @date: 2019/5/20 20:27
     */
    public function users_active_delete(Request $request, UsersActiveAssociationService $activeService)
    {
        $active = $activeService->getActiveInfo(['id' => $request->id]);
        if (!$active) {
            return $this->errorReturn(10001, '该会员已参与活动，不能删除');
        }
        return $activeService->delete($request->id) ? $this->successReturn() : $this->errorReturn();
    }

    /**
     * @param UsersService $usersService
     * @param UsersActiveService $activeService
     * @return \Illuminate\Contracts\Foundation\Application|Factory|View
     */
    public function add_users(UsersService $usersService, UsersActiveService $activeService)
    {
        $userList = $usersService->allUsers();
        $activeList = $activeService->allUsers();
        return view('admin.active.add_users', [
            'userList' => $userList,
            'activeList' => $activeList,
        ]);
    }

    /**
     * 活动参与添加会员
     * @param UsersActiveAssociationRequest $request
     * @param UsersActiveAssociationService $activeAssociationService
     * @param UploadsService $uploadsService
     * @return false|string
     */
    public function add_users_active(UsersActiveAssociationRequest $request, UsersActiveAssociationService $activeAssociationService, UploadsService $uploadsService)
    {
        $params = $request->except(['_token']);

        // 必须上传积分商品图片
        if ($request->file) {
            $path = $uploadsService->uploads_img($request->file);
            if (isset($path->original['status_code']) == 'error') {
                return $this->errorReturn(10001, $path->original['data']);
            }
            $params['active_images'] = $path;
        }
        $active = $activeAssociationService->getActiveInfo(['users_id' => $params['users_id'], 'active_id' => $params['active_id']]);
        if ($active) {
            return $this->errorReturn(10001, '该会员已参与活动');
        }

        unset($params['file']);
        DB::beginTransaction();
        try {
            $addUsers = $activeAssociationService->store($params);
            if (!$addUsers) {
                throw new \Exception('数据库操作异常');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorReturn(10001, $e->getMessage());
        }
        DB::commit();
        return $this->successReturn();
    }

    /**
     * 活动中奖列表
     * @param Request $request
     * @param RewardLogs $rewardLogs
     * @return Factory|View
     * @author:
     * @date: 2019/5/17 15:22
     */
    public function reward_lists(Request $request, RewardLogs $rewardLogs)
    {
        $params = $request->except('_token');
        $where = ['active_id' => $request->id];
        if (isset($params['keywords'])) {
            $where = [
                ['active_name', 'like', '%' . $params['keywords'] . '%', 'or'],
                ['mobile', 'like', '%' . $params['keywords'] . '%', 'or']
            ];
        }
        $usersList = $rewardLogs->getUsers($where);
        return view('admin.active.reward_lists', [
            'request' => $request,
            'search' => $params,
            'usersList' => $usersList
        ]);
    }

    /**
     * 生存活动二维码
     * @param Request $request
     * @param UsersActiveService $activeService
     * @return \Illuminate\Contracts\Foundation\Application|Factory|View
     */
    public function active_qrcode(Request $request, UsersActiveService $activeService)
    {
        $active = $activeService->get($request->id);
        return view('admin.active.active_qrcode', [
            'active' => $active
        ]);
    }


    /**
     * 生存活动二维码
     * @param Request $request
     * @param MiniProgramService $miniProgramService
     * @param HttpService $httpService
     * @param CacheService $cacheService
     * @return false|string
     */
    public function create_qrcode(Request $request, MiniProgramService $miniProgramService,HttpService $httpService,CacheService $cacheService)
    {
        $params = $request->except('_token');
        if(!isset($params['store']) || !isset($params['active_id'])){
            return $this->errorReturn(10001, '请求错误');
        }
        $result = $miniProgramService->getAccessToken($httpService,$cacheService);
        $data = json_decode($result);
        if($data->code == 10001){
            return $result;
        }elseif($data->code == 10000){
            $access_token = $data->info;
            return $miniProgramService->getCreateQrcode($httpService,$access_token,$params);
        }else{
            return $this->errorReturn(10001, '不存在错误');
        }
    }

    /**
     * 活动开奖
     * @param Request $request
     * @param CacheService $cacheService
     * @param RewardLogsService $rewardLogsService
     * @return false|string
     */
    public function reward(Request $request,CacheService $cacheService,RewardLogsService $rewardLogsService){
        $params = $request->except('_token');
        if(!isset($params['active_id'])){
            return $this->errorReturn(10001, '请求错误');
        }

        // 抽奖 直接一二三等奖开奖
        $result1 = $this->getReward($cacheService,$rewardLogsService,self::FIRST_PRIZE_COUNT,$params['active_id'],1);
        if($result1 === true){
            $result2 = $this->getReward($cacheService,$rewardLogsService,self::SECOND_PRIZE_COUNT,$params['active_id'],2);
            if($result2 === true){
                $result3 = $this->getReward($cacheService,$rewardLogsService,self::THIRD_PRIZE_COUNT,$params['active_id'],3);
                if($result3 === true){
                    return $this->successReturn(10000, '开奖成功');
                }else{
                    return $this->errorReturn(10001, '开奖失败3');
                }
            }else{
                return $this->errorReturn(10001, '开奖失败2');
            }
        }else{
            return $this->errorReturn(10001, '开奖失败1');
        }
    }

    /**
     * 活动开奖抽奖流程入库
     * @param $cacheService
     * @param $rewardLogsService
     * @param $randNum
     * @param $active_id
     * @param $level
     * @return bool|false|string
     */
    public function getReward($cacheService,$rewardLogsService,$randNum,$active_id,$level){
        try {
            // 后门设置中奖者
            $rewardList = $rewardLogsService->getUserList(['mobile'],['active_id'=>$active_id,'level'=>$level]);
            $countReward = count($rewardList);
            if($countReward> 0){
                foreach ($rewardList as $value){
                    $cacheService::delList('participate_active_'.$active_id,1,$value->mobile);
                }
            }

            $activeUsers = $cacheService->getList('participate_active_'.$active_id); // 所有参加活动的人
        }catch (\Exception $e){
            return $this->errorReturn(10001, $e->getMessage());
        }
        $count = $randNum-$countReward;
        $rewardCount = array_rand($activeUsers,$count);   // 随机抽取参与活动的
        $rewardUser = [];   // 中奖用户
        // 将随机中奖的用户存到一个新数组
        for ($i=0;$i<$count;$i++){
            array_push($rewardUser,$activeUsers[$rewardCount[$i]]);
        }

        DB::beginTransaction();
        foreach ($rewardUser as $key=>$value){
            $cacheService::delList('participate_active_'.$active_id,1,$value);
            $params['level'] = $level;
            $params['mobile'] = $value;
            $params['active_id'] = $active_id;
            try {
                $rewardLogsService->store($params);
            }catch (\Exception $e){
                DB::rollBack();
                return false;
            }
        }
        DB::commit();
        return true;
    }

    /**
     * 设置中奖会员
     * @param RewardLogsRequest $request
     * @param RewardLogsService $rewardLogsService
     * @return false|string
     */
    public function set_reward(RewardLogsRequest $request, RewardLogsService $rewardLogsService)
    {
        $params = $request->except(['_token']);

        if (!$params['active_id'] || !$params['level'] || !$params['mobile']) {
            return $this->errorReturn(10001, '数据错误，请刷新再试');
        }

        $reward = $rewardLogsService->getActiveInfo(['active_id' => $params['active_id'], 'mobile' => $params['mobile']]);
        if ($reward) {
            return $this->errorReturn(10001, '已设置中奖，请勿重复设置');
        }

        DB::beginTransaction();
        try {
            $addUsers = $rewardLogsService->store($params);
            if (!$addUsers) {
                throw new \Exception('数据库操作异常');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorReturn(10001, $e->getMessage());
        }
        DB::commit();
        return $this->successReturn();
    }


    public function editHeadPortrait()
    {
        return view('admin.edit_head_portrait');
    }
}
